package tools

import (
	"errors"
	"fmt"
	"ruoyi-go/utils"
	"strconv"
	"time"
)

// GenTable model：数据库字段
type GenTable struct {
	TableId        int       `json:"tableId" gorm:"primaryKey"` //表示主键
	TableNames     string    `json:"tableName" gorm:"table_name"`
	TableComment   string    `json:"tableComment" gorm:"table_comment"`
	SubTableName   string    `json:"subTableName" gorm:"sub_table_name"`
	SubTableFkName string    `json:"subTableFkName" gorm:"sub_table_fk_name"`
	ClassName      string    `json:"className" gorm:"class_name"`
	TplCategory    string    `json:"tplCategory" gorm:"tpl_category"`
	PackageName    string    `json:"packageName" gorm:"package_name"`
	ModuleName     string    `json:"moduleName" gorm:"module_name"`
	BusinessName   string    `json:"businessName" gorm:"business_name"`
	FunctionName   string    `json:"functionName" gorm:"function_name"`
	FunctionAuthor string    `json:"functionAuthor" gorm:"function_author"`
	GenType        string    `json:"genType" gorm:"gen_type"`
	GenPath        string    `json:"genPath" gorm:"gen_path"`
	Options        string    `json:"options" gorm:"options"`
	Remark         string    `json:"remark" gorm:"remark"`
	CreateTime     time.Time `gorm:"column:create_time;type:datetime"`
}

// TableName 指定数据库表名称
func (GenTable) TableName() string {
	return "gen_table"
}

// GenTableColumn GenTable model：数据库字段
type GenTableColumn struct {
	ColumnId      int       `json:"columnId" gorm:"primaryKey"` //表示主键
	TableId       string    `json:"tableId" gorm:"table_id"`
	ColumnName    string    `json:"columnName" gorm:"column_name"`
	ColumnComment string    `json:"ColumnComment" gorm:"column_comment"`
	ColumnType    string    `json:"ColumnType" gorm:"column_type"`
	JavaType      string    `json:"javaType" gorm:"java_type"`
	JavaField     string    `json:"javaField" gorm:"java_field"`
	IsPk          string    `json:"isPk" gorm:"is_pk"`
	IsIncrement   string    `json:"isIncrement" gorm:"is_increment"`
	IsRequired    string    `json:"isRequired" gorm:"is_required"`
	IsInsert      string    `json:"isInsert" gorm:"is_insert"`
	IsEdit        string    `json:"isEdit" gorm:"is_edit"`
	IsList        string    `json:"isList" gorm:"is_list"`
	IsQuery       string    `json:"isQuery" gorm:"is_query"`
	QueryType     string    `json:"queryType" gorm:"query_type"`
	HtmlType      string    `json:"htmlType" gorm:"html_type"`
	DictType      string    `json:"dictType" gorm:"dict_type"`
	Sort          int       `json:"sort" gorm:"sort"`
	CreateTime    time.Time `gorm:"column:create_time;type:datetime"`
}

// TableName 指定数据库表名称
func (GenTableColumn) TableName() string {
	return "gen_table_column"
}

type Datetime time.Time

func (t Datetime) MarshalJSON() ([]byte, error) {
	var stamp = fmt.Sprintf("\"%s\"", time.Time(t).Format("2006-01-02 15:04:05"))
	return []byte(stamp), nil
}

type GenDbTable struct {
	TableName    string   `json:"tableName"`
	TableComment string   `json:"tableComment,omitempty"`
	CreateTime   Datetime `json:"createTime,omitempty"`
	UpdateTime   Datetime `json:"updateTime,omitempty"`
}

func SelectGenList(params SearchTableDataParam) TableDataInfo {
	var pageNum = params.PageNum
	var pageSize = params.PageSize
	getTable := params.Other.(GenTable)
	var tableName = getTable.TableNames
	var tableComment = getTable.TableComment

	var beginTime = params.Params.BeginTime
	var endTime = params.Params.EndTime

	var total int64
	db := utils.MysqlDb.Model(GenTable{})

	if tableName != "" {
		db.Where("table_name like concat('%', ?, '%')", tableName)
	}
	if tableComment != "" {
		db.Where("table_comment like concat('%', ?, '%')", tableComment)
	}

	Loc, _ := time.LoadLocation("Asia/Shanghai")
	timeFormat := "2006-01-02 15:04:05"
	startTime1, _ := time.ParseInLocation("2006-01-02", beginTime, Loc)
	endTime = endTime + " 23:59:59"
	endTime1, _ := time.ParseInLocation(timeFormat, endTime, Loc)

	if beginTime != "" {
		db.Where("create_time >= ? and create_time <= ?", startTime1, endTime1)
	}

	if err := db.Count(&total).Error; err != nil {
		return Fail()
	}
	offset := (pageNum - 1) * pageSize
	var rows []GenTable
	db.Offset(offset).Limit(pageSize).Find(&rows)

	if rows == nil {
		return Fail()
	} else {
		return Success(rows, total)
	}
}

// 分页查询
func SelectGenDBList(params SearchTableDataParam) TableDataInfo {
	var pageNum = params.PageNum
	var pageSize = params.PageSize
	getTable := params.Other.(GenTable)
	var tableName = getTable.TableNames
	var tableComment = getTable.TableComment

	offset := (pageNum - 1) * pageSize
	var total int64

	sql := "select table_name, table_comment, create_time, update_time from information_schema.tables " +
		"where table_schema = (select database()) " +
		"AND table_name NOT LIKE 'qrtz_%' " +
		"AND table_name NOT LIKE 'gen_%' " +
		"AND table_name NOT IN (select table_name from gen_table)"
	if tableName != "" {
		sql += "AND lower(table_name) like lower(concat('%" + tableName + "%'))"
	}
	if tableComment != "" {
		sql += "AND lower(table_comment) like lower(concat('%" + tableComment + "%'))"
	}
	db := utils.MysqlDb.Raw(sql)

	if err := db.Count(&total).Error; err != nil {
		// 发送错误信息
		panic(errors.New("发送错误了，错误信息" + err.Error()))
	}

	sql += "LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa(offset)
	var rows []GenDbTable
	utils.MysqlDb.Raw(sql).Scan(&rows)

	if rows == nil {
		return Fail()
	} else {
		return Success(rows, total)
	}
}
